package com.karrim.server.io.sql;


import com.karrim.server.io.sql.def.SQLStream;
import com.karrim.server.io.sql.def.SQLExporter;
import com.karrim.server.io.sql.def.SQLLoader;
import com.karrim.server.io.sql.def.SQLLocator;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author andrea.cantafio
 */
public class AbstractSQLExporter<Connector extends SQLStream> implements SQLExporter<Connector> {

    public AbstractSQLExporter(Connector connector) {
        this.connector = connector;
    }

    public void exportTableDefinition(SQLLoader loader, String table) throws SQLException {
        exportTableDefinition(connector, loader, table);
    }

    @Override
    public void exportTableDefinition(Connector connector, SQLLoader loader, String table) throws SQLException {
        export(loader.getTableDefinition(table).getDefinition());
    }

    public boolean export(final String sql) throws SQLException {
        return export(connector, new SQLLocator() {
            @Override
            public String get() {
                return sql;
            }
        });
    }

    @Override
    public boolean export(Connector d, SQLLocator l) throws SQLException {
        try (Statement s = connector.get().createStatement()) {
            return s.execute(l.get());
        } catch (SQLException sqle) {
            Logger.getLogger(AbstractSQLExporter.class.getName()).log(Level.SEVERE, sqle.toString());
            throw sqle;
        }
    }
    private Connector connector;
}
